package com.example.front.interceptor;

import com.example.gok_mall.constUtil.ConstUtil;
import com.example.gok_mall.entity.User;
import com.example.gok_mall.reponseData.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor{
    /**
     * preHandle方法会在调用任意的Controlle请求前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(ConstUtil.USER_INFO);
        if(userInfo == null){

           ResultData resultData = ResultData.fail("对不起，你没有登陆，请登录后在尝试");

           //将ResultData转成json字符串
           ObjectMapper objectMapper = new ObjectMapper();
           String jsonStr = objectMapper.writeValueAsString(resultData);
           response.getWriter().println(jsonStr);
           return false;
        }
        return true;
    }
}
